package com.oss.weixin.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Prop;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.oss.intercept.jwt.JWTInfo;
import com.oss.intercept.jwt.JWTUtil;
import com.oss.model.Users;
import com.oss.service.DealerService;
import com.oss.service.UsersService;
import com.oss.utils.EmojiUtils;
import com.oss.utils.ZxingKit;
import com.oss.utils.constants.DataDictionary;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import static com.oss.OSSConfig.getApiConfig;
import static com.oss.utils.constants.FolderLocation.LOCAL_PATH;
import static com.oss.utils.constants.FolderLocation.USER_QR;

/**
 * @author Javen 2015年12月5日下午2:20:44
 */
public class WeiXinOauthController extends ApiController {

    JWTUtil jwtUtil = new JWTUtil();

    static Log log = Log.getLog(WeiXinOauthController.class);

    static DealerService dealerService = new DealerService();

    static UsersService usersService = new UsersService();

    // 获取配置文件
    Prop prop = DataDictionary.getProp();

    public void index() {
        ApiConfig apiConfig = getApiConfig();

        String accessToken = this.getCookie("access-token");

        if (accessToken != null) {
            this.setCookie("access-token", null, 0);
        }

        // 用户同意授权，获取code
        String code = getPara("code");

        // 同意授权了
        if (code != null) {
            String appId = apiConfig.getAppId();
            String secret = apiConfig.getAppSecret();

            // 通过code换取网页授权access_token
            SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
            String json = snsAccessToken.getJson();
            log.info(json);

            String token = snsAccessToken.getAccessToken();
            String openId = snsAccessToken.getOpenid();//openid

            // 拉取用户信息(需scope为snsapi_userinfo)
            ApiResult apiResult = SnsApi.getUserInfo(token, openId);

            if (apiResult.isSucceed()) {
                //查找是否已经注册了
                Users users = usersService.findByOpendId(openId);

                if (users != null) {
                    JWTInfo jwtInfo = new JWTInfo(users.getNickname(), String.valueOf(users.getId()), openId);
                    try {
                        accessToken = jwtUtil.generateToken(jwtInfo);
                    } catch (Exception e) {
                        LogKit.info("token 生成失败：" + e);
                    }

                    this.setCookie("access-token", accessToken, DataDictionary.getProp().getInt("tokenExpired"));

                    if (users.getMobile() == null) {
                        redirect(prop.get("regist_url"));
                        return;
                    }

                    //跳转至个人中心
                    redirect(prop.get("user_center_url"));
                    return;
                } else {
                    JSONObject jsonObject = JSON.parseObject(apiResult.getJson());

                    String nickName = jsonObject.getString("nickname");//需要做转换，避免无法保存表情
                    try {
                        nickName = EmojiUtils.emojiConvert1(nickName);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    // 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
                    int sex = jsonObject.getIntValue("sex");
                    //头像
                    String headimgurl = jsonObject.getString("headimgurl");

                    //新建用户
                    users = new Users();
                    users.setOpenId(openId);
                    users.setNickname(nickName);
                    users.setHeadImgUrl(headimgurl);
                    users.setMemberCode(DateUtil.format(new Date(), "yyyyMMdd") + RandomUtil.randomNumbers(5));//用户编码
                    users.setGender(sex);
                    users.setCreateTime(new Date());
                    users.save();
                }

                JWTInfo jwtInfo = new JWTInfo(users.getNickname(), String.valueOf(users.getId()), openId);
                try {
                    accessToken = jwtUtil.generateToken(jwtInfo);
                } catch (Exception e) {
                    LogKit.info("token 生成失败：" + e);
                }

                this.setCookie("access-token", accessToken, DataDictionary.getProp().getInt("tokenExpired"));

                //跳转到注册页面
                redirect(prop.get("regist_url"));
            } else {
                Users users = new Users();
                users.setOpenId(openId);
                users.setMemberCode(DateUtil.format(new Date(), "yyyyMMdd") + RandomUtil.randomNumbers(5));//用户编码
                users.setCreateTime(new Date());
                users.save();
                //跳转到注册页面
                redirect(prop.get("regist_url"));
            }
        } else {
            renderText("code is  null");
        }
    }

    /**
     * PC扫码登陆回调 获取AccessToken以及用户信息跟微信公众号授权用户用户信息一样
     */
    public void webCallBack() {
        // 用户同意授权，获取code
        String code = getPara("code");
        String state = getPara("state");
        if (code != null) {
            System.out.println("code>" + code + " state>" + state);
            String appId = prop.get("webAppId");
            String secret = prop.get("webAppSecret");
            // 通过code换取网页授权access_token
            SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appId, secret, code);
            String json = snsAccessToken.getJson();
            System.out.println("通过code获取access_token>>" + json);
            String token = snsAccessToken.getAccessToken();
            String openId = snsAccessToken.getOpenid();
            // 拉取用户信息(需scope为 snsapi_userinfo)
            ApiResult apiResult = SnsApi.getUserInfo(token, openId);

            log.warn("getUserInfo:" + apiResult.getJson());
            if (apiResult.isSucceed()) {
                JSONObject jsonObject = JSON.parseObject(apiResult.getJson());
                String nickName = jsonObject.getString("nickname");
                // 用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
                int sex = jsonObject.getIntValue("sex");
                String city = jsonObject.getString("city");// 城市
                String province = jsonObject.getString("province");// 省份
                String country = jsonObject.getString("country");// 国家
                String headimgurl = jsonObject.getString("headimgurl");
                String unionid = jsonObject.getString("unionid");
            }
            renderText("通过code获取access_token>>" + json + "  \n" + "getUserInfo:" + apiResult.getJson());
        }

    }

}
